<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 推广系统控制器
 * @author [xiazhang] 
 * @date(2016-05-25)
 */
class Invite extends CI_Controller {
	private $user_info;
	private $object = 'cny';

	public function __construct(){  
        parent::__construct();
        $this->load->library('passPort');
        $this->passportClass = $this->passport;
        
        $this->passportClass->setPlatform($this->config->item('platform'));//设置平台
		$this->user_info = $this->passportClass->checkCookieAuthCode('','',true);

		$this->load->library('CI_Wechat');
		
    }

	public function index(){
		$get = $this->input->get();
		$tobemaster = isset($get['tobemaster'])?$get['tobemaster']:0;
		if($tobemaster == 1){
			$this->load->model('user_model');
			$data = array(
           	 	'invite_flag' => 1
	        );
	        $whereArr = array(
	            'uid' => $this->user_info['uid']
	        );
	        $this->user_model->updateUser($data,$whereArr);
	        $this->passportClass->flushUserCache($this->user_info['uid']);
		}
		if($this->user_info['invite_flag']==0 && $tobemaster==0){
			redirect('/invite/help');
			die;
		}

		$this->load->library('Referrals');
        $vip		=	$this->referrals->getInviteVip($this->user_info['uid']);
		//$this->load->library('Referrals');
        //$this->referrals->getInviteByMaster('100062','oYUCks6fQroyN_Y-_VHQn6d3Yo0A');die;
		
		$assign['vip']			= $vip;
		$assign['user_info']	= $this->user_info;
		$assign['userData']		= $this->user_info;
    	$qrCode = $this->ci_wechat->getQRCode($this->user_info['uid'],2);
		// $assign['qrCode']= $this->ci_wechat->getQRUrl($qrCode['ticket']);
		// var_export($qrCode);
		// echo $assign['qrCode'];
		$assign['url'] = $qrCode['url'];
		$this->load->view('invite/index',$assign);
	}

	public function poster(){
		$qrCode = $this->ci_wechat->getQRCode($this->user_info['uid'],2);
		$assign['url'] = $qrCode['url'];
		$this->load->view('invite/poster',$assign);
	}

	public function showqrcode(){
		$uid = $this->user_info['uid'];
		$get = $this->input->get();
		require_once(PUBPATH . 'third_party/qrcode/phpqrcode.php');
		$value = $get['url'];//二维码内容 
		$errorCorrectionLevel = 'L';//容错级别 
		$matrixPointSize = 6;//生成图片大小 
		$filename = '/tmp/log/qrcode/'.$uid.'.png';
		//生成二维码图片 
		QRcode::png($value, $filename, $errorCorrectionLevel, $matrixPointSize, 2); 
		$logo =  '/mnt/public/img/logo2.jpg';//准备好的logo图片 
		$QR = $filename;//已经生成的原始二维码图 
		 
		if ($logo !== FALSE) { 
		 	$QR = imagecreatefromstring(file_get_contents($QR)); 
		 	$logo = imagecreatefromstring(file_get_contents($logo)); 
		 	$QR_width = imagesx($QR);//二维码图片宽度 
		 	$QR_height = imagesy($QR);//二维码图片高度 
		 	$logo_width = imagesx($logo);//logo图片宽度 
		 	$logo_height = imagesy($logo);//logo图片高度 
		 	$logo_qr_width = $QR_width / 6; 
		 	$scale = $logo_width/$logo_qr_width; 
		 	$logo_qr_height = $logo_height/$scale; 
		 	$from_width = ($QR_width - $logo_qr_width) / 2; 
		 	//重新组合图片并调整大小 
		 	imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height); 
		}
		//输出图片 
		Header("Content-type: image/png");
		ImagePng($QR);
	}

	public function callback(){
		$get = $this->input->get();
		$code = $get['code'];
		$state = $get['state'];
		$redirect = isset($get['redirect'])?"/".$get['redirect']:'/';
		if($state!='sfc32lSdj45dfo2sdd23GdKLm') die('系统错误[10000]！');
		writeDebug('['.date('Y-m-d H:i:s').'] get='.var_export($get,true), "callback");
		$data = $this->ci_wechat->getOauthAccessToken($code);
		writeDebug('['.date('Y-m-d H:i:s').'] data='.var_export($data,true), "callback");
		if(!$data) redirect("/invite");
		$openid = $data['openid'];
		$oauthUserInfo = $this->ci_wechat->getOauthUserinfo($data['access_token'],$openid);
		
		//检查是否已经注册
		$this->load->model('user_model');
		$whereArr = array(
        	'platform' => 1,//平台
        	'openid' => $openid,
        );
		$userData = $this->user_model->getUserInfoByMulti($whereArr,true);

		$platform = $this->config->item('platform');//平台
		$this->load->library('session');
		$sessid = $this->session->session_id;

		//链接redis
		$this->load->driver('cache');
		$this->cache->redis->is_supported();
		$this->cache->redis->getClient()->set("$platform|WechatCallback|$sessid",$openid);
		$this->cache->redis->getClient()->expire("$platform|WechatCallback|$sessid",43200);
		$_SESSION['openid'] = $openid;
		if(empty($userData)){//没有注册，跳转到注册页面
			if($openid=='oYUCkswy39ISm6KOYsUA165UlKWY1'){
				$this->setTestOP("$platform|WechatCallback|$sessid",$openid);
				redirect("https://test.2800.com/invite/help?tobemaster=2");
			}else{
				redirect("/invite/help?tobemaster=2");
			}
		}else{//已经注册直接跳转到首页
	        if($userData['login_flag']==1){//，免密码登陆
	        	$uid = $userData['uid'];
	        	$platform = $this->config->item('platform');//平台
        		$cooper = $this->config->item('cooper');

	        	$this->load->library('passPort');
		        $this->passport->setPlatform($platform);
		        $this->passport->setCooper($cooper);
	        	//是否禁止帐号重复登录
	            if($userData['online_flag']==1){
	                $onlineArr = $this->passport->checkOnline($uid);
	                if(!empty($onlineArr)) foreach($onlineArr as $items){
	                    $this->passport->kickOffline($items['skey']);
	                }
	            }
	            $randPass = md5($this->passport->makeRandPassword());//取得随机密码[用于检验cookie中所存加密字符串正确性]
	            // $this->passport->setExpire($userInfo['cache_expire']);//设置在线误操作过期时间
	            $this->passport->saveOnlineInfo($uid, $randPass);
	            //提出已经超时的用户
	            $this->passport->deleteOverTime();
	            $this->passport->setCookie('wcp_openid',$openid);
	            $this->user_info = $userData;
	            /***********登录记录LOG Start************/
	            $ip = get_ip();
	            $system = getSystem();
	            $browser = getBrowser();
	            $datetime = date('Y-m-d H:i:s');
	            $loginLog   =   array(
	                    'uid' => $uid,
	                    'cooper' => $cooper,
	                    'comefrom' => 2,//1pc 2手机
	                    'system' => $system,
	                    'browser' => $browser,
	                    'ip' => $ip,
	                    'platform' => $platform,
	                    'create_time' => $datetime,
	            );
	            $this->user_model->addLoginLog($loginLog);
	            /***********登录记录LOG End************/
	        }

			if($userData['invite_flag']==0){//还不是经纪人
				if(!empty($this->user_info)){//已经注册账户，还不是经纪人,已经登陆
					if($openid=='oYUCkswy39ISm6KOYsUA165UlKWY1'){
						$this->setTestOP("$platform|WechatCallback|$sessid",$openid);
						redirect("https://test.2800.com/invite/help?tobemaster=1");
					}else{
						redirect("/invite/help?tobemaster=1");
					}
				}
			}
			if($openid=='oYUCkswy39ISm6KOYsUA165UlKWY1'){
				redirect("https://test.2800.com/invite");
			}
			
			$data = array(
	            'nickname' => $oauthUserInfo['nickname']
	        );
	        $whereArr = array(
	            'platform' => 1,//平台
        		'openid' => $openid,
	        );

	        $rs = $this->user_model->updateUser($data,$whereArr);
	        $qrCode = $this->ci_wechat->getQRCode($userData['uid'],2);
        	$assign['user_info'] = $this->user_info;
        	$assign['userData'] = $userData;
        	$assign['url'] = $qrCode['url'];
        	$this->load->view('invite/index',$assign);
		}
	}

	/**
	 * 设置测试账号跳转到test.2800.com
	 */
	private function setTestOP($key,$val){
		$redis = new Redis();
		$redis->connect('115.29.241.200',6379,0);
		$redis->select(3);
		$rs = $redis->set($key,$val);
	}

	public function help(){
		$get = $this->input->get();
		$tobemaster = isset($get['tobemaster'])?$get['tobemaster']:0;
		$assign['title']	=	"经纪人介绍";
		$assign['user_info'] = $this->user_info;
		$assign['tobemaster'] = $tobemaster;
		$this->load->view('invite/help',$assign);
	}

	public function earn(){
		redirect("/invite");
		if(empty($this->user_info)){
			redirect("/invite");
		}
		$this->load->library('Referrals');
        $vip		=	$this->referrals->getInviteVip($this->user_info['uid']);
		if(!empty($vip)){
			redirect("/invite");
		}

        $details	=	$this->referrals->getInviteByMaster($this->user_info['uid']);
		$earn		=	0;
		if(!empty($details)) foreach($details as $key=>$items){
			$earn	=	bcadd($items['cny'],$earn,2);
		}
		
		$date		=	date("Y-m-d",strtotime("-29 days"));
		$where		=	array('master'=>$this->user_info['uid']);
		$earn_data	=	$this->referrals->getEarn($where,$date);
		$day_data	=	array();
		$month_earn	=	0;
		if(!empty($earn_data)) foreach($earn_data as $items){
			$day_data[$items['date']]['trade_cny']	=	isset($day_data[$items['date']]['trade_cny'])?bcadd($items['trade_cny'],$day_data[$items['date']]['trade_cny'],2):$items['trade_cny'];
			$day_data[$items['date']]['earn']	=	isset($day_data[$items['date']]['earn'])?bcadd($items['cny'],$day_data[$items['date']]['earn'],2):$items['cny'];
			$day_data[$items['date']]['rate']	=	$items['rate'];
			$month_earn		=	bcadd($items['cny'],$month_earn,2);
		}

		$assign['day_data']		= $day_data;
		$assign['earn']			= $earn;
		$assign['month_earn']	= $month_earn;
		$assign['title']		= "我的收入";
		$this->load->view('invite/earn',$assign);
	}

	public function details(){
		if(empty($this->user_info)){
			redirect("/invite");
		}
		$assign['user_info']	= $this->user_info;

		$this->load->library('Referrals');
		$vip		=	$this->referrals->getInviteVip($this->user_info['uid']);
        $details	=	$this->referrals->getInviteByMaster($this->user_info['uid']);
		$type		=	!empty($vip)?"yk":"cash";
		$deal		=	array();
		$invite_num	=	0;

		$this->load->model('user_model');
		$this->load->library('Statistics');


		if(!empty($details)) foreach($details as $key=>$items){
			$user_info	=	$this->user_model->getUserByUid($items['slave']);
			$details[$key]['nickname']	=	$user_info['nickname'];

			$trade		=	$this->statistics->getTradeTotalByUid($items['slave']);
			if(!empty($vip)){
				$tradeStatistics[$type]	=	!empty($trade)?bcadd($trade['yk'],$trade['ticket_yk'],2):"0.00";
				$invite					=	$this->referrals->getInviteCnyByMaster($items['slave']);
				$tradeStatistics[$type]	=	bcsub($tradeStatistics[$type],$invite['cny'],2);
			}else{
				$tradeStatistics[$type]	=	!empty($trade)?$trade['cny']:"0.00";
			}

			$invite_num				+=	1;
			$deal[$type]			=	bcadd($tradeStatistics[$type],$deal[$type],2);
			$details[$key][$type]	=	bcadd($tradeStatistics[$type],0,2);
		}

		$assign['details']		= $details;
		$assign['deal']			= $deal;
		$assign['type']			= $type;
		$assign['invite_num']	= $invite_num;
		$assign['title']		= "推荐明细";
		$this->load->view('invite/details',$assign);
	}

	/*public function tradeDetails(){
		if(empty($this->user_info)){
			redirect("/invite");
		}
		$assign['user_info']	= $this->user_info;

		$this->load->library('Referrals');
        $vip		=	$this->referrals->getInviteVip($this->user_info['uid']);
        $details	=	$this->referrals->getInviteByMaster($this->user_info['uid']);
		$type		=	!empty($vip)?"yk":"cash";

		$this->load->model('user_model');
		$this->load->model('cfd_model');

		if(!empty($vip)){
			$trade['where']		=	array('kp'=>'close');
			$trade['source_in']	=	array();
		}else{
			$trade['where']		=	array('dtype'=>'cny');
			$trade['source_in']	=	array('10001','50001');
		}

		$date		=	date("Y-m-d",strtotime("-29 days"));
		$now_date	=	date("Y-m-d");
		$day_data	=	array();
		$today_deal	=	$month_deal	=	array();

		if(!empty($details)) foreach($details as $key=>$items){
			$slave		=	$items['slave'];
			$user_info	=	$this->user_model->getUserByUid($slave);
			$details[$key]['nickname']	=	$user_info['nickname'];
			
			$trade['where']['uid']	=	$items['slave'];

			if(!empty($vip)){
				$tradeStatistics		=	$this->cfd_model->getTradeYk($trade,$date);
			}else{
				$tradeStatistics		=	$this->cfd_model->getTradeStatistics($trade,$date);
			}

			if(!empty($tradeStatistics)) foreach($tradeStatistics as $items){
				$day					=	date("Y-m-d",strtotime($items['date']));
				if(!empty($vip)){
					if($day == date("Y-m-d")) continue;
				}

				$day_data[$day]			=	isset($day_data[$day])?bcadd($items[$type],$day_data[$day],2):bcadd($items[$type],0,2);
				$details[$key][$day]	=	isset($details[$key][$day])?bcadd($items[$type],$details[$key][$day],2):bcadd($items[$type],0,2);
				if($day == date("Y-m-d")){
					$today_deal[$type]	=	bcadd($items[$type],$today_deal[$type],2);
				}
				$month_deal[$type]	=	bcadd($items[$type],$month_deal[$type],2);
			}

			if(!empty($vip)){
				for($kdate=$date;$kdate<=$now_date;){
					$where		=	array('master'=>$slave,'date'=>$kdate);
					$invite		=	$this->referrals->getInviteDetails($where);
					if($invite['cny'] >0){
						$day_data[$kdate]		=	bcsub($day_data[$kdate],$invite['cny'],2);
						$details[$key][$kdate]	=	bcsub($details[$key][$kdate],$invite['cny'],2);
						if($kdate == date("Y-m-d")){
							$today_deal[$type]		=	bcsub($today_deal[$type],$invite['cny'],2);
						}
						$month_deal[$type]		=	bcsub($month_deal[$type],$invite['cny'],2);
					}
					$kdate	=	date("Y-m-d",strtotime($kdate)+24*3600);
				}
			}
		}
		krsort($day_data);
		$assign['day_data']			= $day_data;
		$assign['details']			= $details;
		$assign['today_deal']		= $today_deal;
		$assign['month_deal']		= $month_deal;
		$assign['type']				= $type;
		$assign['title']			= "交易明细";
		$this->load->view('invite/tradeDetails',$assign);
	}*/

	public function tradeDetails(){
		if(empty($this->user_info)){
			redirect("/invite");
		}
		$assign['user_info']	= $this->user_info;

		$this->load->library('Referrals');
        $vip		=	$this->referrals->getInviteVip($this->user_info['uid']);
        $details	=	$this->referrals->getInviteByMaster($this->user_info['uid']);
		$type		=	!empty($vip)?"yk":"cash";

		$this->load->model('user_model');
		$this->load->model('cfd_model');
		$this->load->library('Statistics');

		$date		=	date("Y-m-d",strtotime("-29 days"));
		$now_date	=	date("Y-m-d");
		$day_data	=	array();
		$today_deal	=	$month_deal	=	array();

		if(!empty($details)) foreach($details as $key=>$items){
			$slave		=	$items['slave'];
			$user_info	=	$this->user_model->getUserByUid($slave);
			$details[$key]['nickname']	=	$user_info['nickname'];
			
			//计算今日交易额
			$trade			=	array(
				'where'		=>	array('dtype'=>'cny','uid'=>$slave),
				'source_in'	=>	array('10001','50001'),
			);
			$todayTrade			=	$this->cfd_model->getTradeStatistics($trade,$now_date);
			if(!empty($todayTrade)) foreach($todayTrade as $items){
				$day				=	date("Y-m-d",strtotime($items['date']));

				$day_data[$day]		=	isset($day_data[$day])?bcadd($items[$type],$day_data[$day],2):bcadd($items[$type],0,2);
				$details[$key][$day]	=	isset($details[$key][$day])?bcadd($items[$type],$details[$key][$day],2):bcadd($items[$type],0,2);
				
				$today_deal[$type]	=	bcadd($items[$type],$today_deal[$type],2);
				$month_deal[$type]	=	bcadd($items[$type],$month_deal[$type],2);
			}
			
			//计算前29天交易额或盈亏
			$trade				=	array('uid'=>$slave);
			$tradeStatistics	=	$this->statistics->getTrade($trade,$date);

			if(!empty($tradeStatistics)) foreach($tradeStatistics as $items){
				$day				=	date("Y-m-d",strtotime($items['date']));

				if(!empty($vip)){
					$items[$type]	=	bcadd($items['yk'],$items['ticket_yk'],2);
				}else{
					$items[$type]	=	bcadd($items['cny'],0,2);
				}
				$day_data[$day]		=	isset($day_data[$day])?bcadd($items[$type],$day_data[$day],2):bcadd($items[$type],0,2);
				$details[$key][$day]	=	isset($details[$key][$day])?bcadd($items[$type],$details[$key][$day],2):bcadd($items[$type],0,2);

				$month_deal[$type]	=	bcadd($items[$type],$month_deal[$type],2);
			}
			
			//盈亏去掉普通经纪人提成
			if(!empty($vip)){
				for($kdate=$date;$kdate<$now_date;){
					$where		=	array('master'=>$slave,'date'=>$kdate);
					$invite		=	$this->referrals->getInviteDetails($where);
					if($invite['cny'] >0){
						$day_data[$kdate]		=	bcsub($day_data[$kdate],$invite['cny'],2);
						$details[$key][$kdate]	=	bcsub($details[$key][$kdate],$invite['cny'],2);
						$month_deal[$type]		=	bcsub($month_deal[$type],$invite['cny'],2);
					}
					$kdate	=	date("Y-m-d",strtotime($kdate)+24*3600);
				}
			}
		}
		krsort($day_data);
		$assign['day_data']			= $day_data;
		$assign['details']			= $details;
		$assign['today_deal']		= $today_deal;
		$assign['month_deal']		= $month_deal;
		$assign['type']				= $type;
		$assign['title']			= "交易明细";
		$this->load->view('invite/tradeDetails',$assign);
	}

}
